package main.java.DMDE.infrastructure.visual;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

import main.java.DMDE.model.Diagram;
import main.java.DMDE.model.Entity;
import main.java.DMDE.model.relationships.Relationship;
import main.java.DMDE.infrastructure.IProjectContext;


public class DiagramTreeNode extends DefaultMutableTreeNode {

    private static final long serialVersionUID = 1L;

    private static String SubDiagramsNodeName = "Sub-Diagrams";
    private static String EntitiesNodeName = "Entities";
    private static String RelationshipsNodeName = "Relationships";

    private DefaultMutableTreeNode subdiagramsNode;
    private DefaultMutableTreeNode entitiesNode;
    private DefaultMutableTreeNode relationshipsNode;
    
    private Diagram diagram;

    private IProjectContext projectContext;

    public DiagramTreeNode(Diagram diagram, IProjectContext projectContext) {
	super(diagram);
	this.projectContext = projectContext;
	this.diagram = diagram;
	this.addChildFolders();
	this.populateEntities();
	populateRelationships();
    }

    private void populateEntities() {
	for (Entity entity : this.diagram.getEntities()) {
	    this.entitiesNode.add(new DefaultMutableTreeNode(entity));
	}
    }
    
    private void populateRelationships() {
	for (Relationship relationship : this.diagram.getRelationships()) {
	    this.relationshipsNode.add(new DefaultMutableTreeNode(relationship));
	}
    }

    public Diagram getDiagram() {
	return this.diagram;
    }

    private void addChildFolders() {
	this.entitiesNode = new DefaultMutableTreeNode(EntitiesNodeName);
	this.relationshipsNode = new DefaultMutableTreeNode(RelationshipsNodeName);
	this.subdiagramsNode = new DefaultMutableTreeNode(SubDiagramsNodeName);
	this.add(this.entitiesNode);
	this.add(this.relationshipsNode);
	this.add(this.subdiagramsNode);
    }

    public void addEntity(Entity entity, DefaultTreeModel tree) {
	this.entitiesNode.add(new DefaultMutableTreeNode(entity));
	int index = this.entitiesNode.getChildCount() - 1;
	tree.nodesWereInserted(this.entitiesNode, new int[] { index });
    }
    
    @Override
    public String toString() {
        return diagram.getName();
    }

    public void addRelationship(Relationship relationship,DefaultTreeModel tree) {
	this.relationshipsNode.add(new DefaultMutableTreeNode(relationship));
	int index = this.relationshipsNode.getChildCount() - 1;
	tree.nodesWereInserted(this.relationshipsNode, new int[] { index });
    }

    public DiagramTreeNode addSubdiagram(Diagram diagram,DefaultTreeModel tree) {
	DiagramTreeNode diagramNode = new DiagramTreeNode(diagram, this.projectContext);
	this.subdiagramsNode.add(diagramNode);
	int index = this.subdiagramsNode.getChildCount() - 1;
	tree.nodesWereInserted(this.subdiagramsNode, new int[]{index});
	return diagramNode;
    }
}
